import Router from 'koa-router';
import { pool } from '../../config/database';
import { authMiddleware } from '../../middleware/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { ApiResponse, Address, AddressCreateInput, AddressUpdateInput } from '../../types';

const router = new Router({ prefix: '/api/addresses' });

// 获取用户地址列表
router.get('/', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.state.user.id as number;

    const [addresses] = await pool.execute(
      'SELECT * FROM addresses WHERE user_id = ? ORDER BY is_default DESC, created_at DESC',
      [userId]
    ) as [RowDataPacket[], any];

    ctx.body = {
      success: true,
      data: addresses as Address[]
    } as ApiResponse;

  } catch (error) {
    console.error('获取地址列表失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取地址列表失败'
    } as ApiResponse;
  }
});

// 获取地址详情
router.get('/:id', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.state.user.id as number;
    const addressId = parseInt(ctx.params.id);

    const [addresses] = await pool.execute(
      'SELECT * FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, userId]
    ) as [RowDataPacket[], any];

    if (addresses.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '地址不存在或无权限'
      } as ApiResponse;
      return;
    }

    ctx.body = {
      success: true,
      data: addresses[0] as Address
    } as ApiResponse;

  } catch (error) {
    console.error('获取地址详情失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取地址详情失败'
    } as ApiResponse;
  }
});

// 获取默认地址
router.get('/default', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.state.user.id as number;

    const [addresses] = await pool.execute(
      'SELECT * FROM addresses WHERE user_id = ? AND is_default = TRUE',
      [userId]
    ) as [RowDataPacket[], any];

    ctx.body = {
      success: true,
      data: addresses.length > 0 ? addresses[0] as Address : null
    } as ApiResponse;

  } catch (error) {
    console.error('获取默认地址失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取默认地址失败'
    } as ApiResponse;
  }
});

// 创建新地址
router.post('/', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.state.user.id as number;
    const addressData = ctx.request.body as AddressCreateInput;

    const { name, phone, province, city, district, detail, postal_code, is_default } = addressData;

    if (!name || !phone || !province || !city || !district || !detail) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '收货人姓名、手机号、省市区和详细地址不能为空'
      } as ApiResponse;
      return;
    }

    // 如果设为默认地址，先取消其他默认地址
    if (is_default) {
      await pool.execute(
        'UPDATE addresses SET is_default = FALSE WHERE user_id = ?',
        [userId]
      );
    }

    // 创建新地址
    const [result] = await pool.execute(
      'INSERT INTO addresses (user_id, name, phone, province, city, district, detail, postal_code, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [userId, name, phone, province, city, district, detail, postal_code || null, is_default || false]
    ) as [ResultSetHeader, any];

    // 获取创建的地址信息
    const [addresses] = await pool.execute(
      'SELECT * FROM addresses WHERE id = ?',
      [result.insertId]
    ) as [RowDataPacket[], any];

    ctx.body = {
      success: true,
      data: addresses[0] as Address,
      message: '地址添加成功'
    } as ApiResponse;

  } catch (error) {
    console.error('创建地址失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '创建地址失败'
    } as ApiResponse;
  }
});

// 更新地址
router.put('/:id', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.state.user.id as number;
    const addressId = parseInt(ctx.params.id);
    const updateData = ctx.request.body as AddressUpdateInput;

    // 检查地址是否属于当前用户
    const [existingAddresses] = await pool.execute(
      'SELECT id FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, userId]
    ) as [RowDataPacket[], any];

    if (existingAddresses.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '地址不存在或无权限'
      } as ApiResponse;
      return;
    }

    // 构建更新字段
    const fields = [];
    const values = [];

    for (const [key, value] of Object.entries(updateData)) {
      if (value !== undefined) {
        fields.push(`${key} = ?`);
        values.push(value);
      }
    }

    if (fields.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '没有需要更新的字段'
      } as ApiResponse;
      return;
    }

    // 如果设为默认地址，先取消其他默认地址
    if (updateData.is_default) {
      await pool.execute(
        'UPDATE addresses SET is_default = FALSE WHERE user_id = ? AND id != ?',
        [userId, addressId]
      );
    }

    fields.push('updated_at = CURRENT_TIMESTAMP');
    values.push(addressId, userId);

    // 更新地址
    await pool.execute(
      `UPDATE addresses SET ${fields.join(', ')} WHERE id = ? AND user_id = ?`,
      values
    );

    // 获取更新后的地址信息
    const [addresses] = await pool.execute(
      'SELECT * FROM addresses WHERE id = ?',
      [addressId]
    ) as [RowDataPacket[], any];

    ctx.body = {
      success: true,
      data: addresses[0] as Address,
      message: '地址更新成功'
    } as ApiResponse;

  } catch (error) {
    console.error('更新地址失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '更新地址失败'
    } as ApiResponse;
  }
});

// 删除地址
router.delete('/:id', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.state.user.id as number;
    const addressId = parseInt(ctx.params.id);

    // 检查地址是否属于当前用户
    const [existingAddresses] = await pool.execute(
      'SELECT id, is_default FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, userId]
    ) as [RowDataPacket[], any];

    if (existingAddresses.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '地址不存在或无权限'
      } as ApiResponse;
      return;
    }

    // 删除地址
    await pool.execute(
      'DELETE FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, userId]
    );

    // 如果删除的是默认地址，将第一个地址设为默认
    if (existingAddresses[0].is_default) {
      const [remainingAddresses] = await pool.execute(
        'SELECT id FROM addresses WHERE user_id = ? ORDER BY created_at ASC LIMIT 1',
        [userId]
      ) as [RowDataPacket[], any];

      if (remainingAddresses.length > 0) {
        await pool.execute(
          'UPDATE addresses SET is_default = TRUE WHERE id = ?',
          [remainingAddresses[0].id]
        );
      }
    }

    ctx.body = {
      success: true,
      message: '地址删除成功'
    } as ApiResponse;

  } catch (error) {
    console.error('删除地址失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '删除地址失败'
    } as ApiResponse;
  }
});

// 设置默认地址
router.put('/:id/default', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.state.user.id as number;
    const addressId = parseInt(ctx.params.id);

    // 检查地址是否属于当前用户
    const [existingAddresses] = await pool.execute(
      'SELECT id FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, userId]
    ) as [RowDataPacket[], any];

    if (existingAddresses.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '地址不存在或无权限'
      } as ApiResponse;
      return;
    }

    // 先取消所有默认地址
    await pool.execute(
      'UPDATE addresses SET is_default = FALSE WHERE user_id = ?',
      [userId]
    );

    // 设置新的默认地址
    await pool.execute(
      'UPDATE addresses SET is_default = TRUE WHERE id = ? AND user_id = ?',
      [addressId, userId]
    );

    ctx.body = {
      success: true,
      message: '默认地址设置成功'
    } as ApiResponse;

  } catch (error) {
    console.error('设置默认地址失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '设置默认地址失败'
    } as ApiResponse;
  }
});

export default router;